package com.test.javafaq_portal.controller;


import com.test.javafaq_portal.service.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@Slf4j
public class HomeController {

    //声明两个角色常量
    static final GrantedAuthority STUDENT = new SimpleGrantedAuthority("ROLE_STUDENT");
    static final GrantedAuthority TEACHER = new SimpleGrantedAuthority("ROLE_TEACHER");

    @GetMapping("/question/detail.html")
    public ModelAndView detail(@AuthenticationPrincipal UserDetails user){
        if(user.getAuthorities().contains(STUDENT)){
            return new ModelAndView("question/detail");
        } else if (user.getAuthorities().contains(TEACHER)) {
            return new ModelAndView("question/detail_teacher.html");
        }

        throw ServiceException.invalidRequest("没有登陆/身份不能识别!");
    }


    @GetMapping("/index.html")
    public ModelAndView index(@AuthenticationPrincipal User user){
        //@AuthenticationPrincipal表示从springsecurity中获得用户信息
        if(user.getAuthorities().contains(STUDENT)){
            System.out.println("我是学生");
            return new ModelAndView("index");
        }else if(user.getAuthorities().contains(TEACHER)){
            System.out.println("我是讲师");
            return new ModelAndView("index_teacher");
        }
        return null;
    }

//    @GetMapping("/index.html")
//    public ModelAndView index(){
//        return new ModelAndView("index");
//    }
//
//    @GetMapping("/index_teacher.html")
//    public ModelAndView indexTeacher(){
//        return new ModelAndView("index_teacher");
//    }

    @GetMapping("/question/create.html")
    public ModelAndView createQuestion(){
        return new ModelAndView("question/create");
    }

}
